using Admin2025.Application.Dtos;
using Admin2025.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Admin2025.Api.Controllers;

/// <summary>
/// 文件上传控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
// [Authorize] // 需要认证
public class FileUploadController : ControllerBase
{
    private readonly IFileUploadService _fileUploadService;
    private readonly ILogger<FileUploadController> _logger;

    public FileUploadController(
        IFileUploadService fileUploadService,
        ILogger<FileUploadController> logger)
    {
        _fileUploadService = fileUploadService;
        _logger = logger;
    }

    /// <summary>
    /// 上传单个文件
    /// </summary>
    /// <param name="file">上传的文件</param>
    /// <param name="category">文件分类（可选）</param>
    /// <returns>上传结果</returns>
    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile(IFormFile file, [FromQuery] string? category = null)
    {
        try
        {
            if (file == null)
            {
                return BadRequest(new { message = "请选择要上传的文件" });
            }

            var result = await _fileUploadService.UploadFileAsync(file, category);
            
            if (result.Succeeded)
            {
                return Ok(result);
            }
            
            return BadRequest(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件上传失败");
            return StatusCode(500, new { message = "文件上传失败" });
        }
    }

    /// <summary>
    /// 批量上传文件
    /// </summary>
    /// <param name="files">上传的文件列表</param>
    /// <param name="category">文件分类（可选）</param>
    /// <returns>批量上传结果</returns>
    [HttpPost("upload-batch")]
    public async Task<IActionResult> UploadFiles(IFormFileCollection files, [FromQuery] string? category = null)
    {
        try
        {
            if (files == null || files.Count == 0)
            {
                return BadRequest(new { message = "请选择要上传的文件" });
            }

            var result = await _fileUploadService.UploadFilesAsync(files, category);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量文件上传失败");
            return StatusCode(500, new { message = "批量文件上传失败" });
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fileId">文件ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{fileId}")]
    public async Task<IActionResult> DeleteFile(string fileId)
    {
        try
        {
            var result = await _fileUploadService.DeleteFileAsync(fileId);
            
            if (result.Succeeded)
            {
                return Ok(result);
            }
            
            return result.Code == 404 ? NotFound(result) : BadRequest(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件删除失败: {FileId}", fileId);
            return StatusCode(500, new { message = "文件删除失败" });
        }
    }

    /// <summary>
    /// 获取文件信息
    /// </summary>
    /// <param name="fileId">文件ID</param>
    /// <returns>文件信息</returns>
    [HttpGet("{fileId}")]
    public async Task<IActionResult> GetFileInfo(string fileId)
    {
        try
        {
            var result = await _fileUploadService.GetFileInfoAsync(fileId);
            
            if (result.Succeeded)
            {
                return Ok(result);
            }
            
            return result.Code == 404 ? NotFound(result) : BadRequest(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文件信息失败: {FileId}", fileId);
            return StatusCode(500, new { message = "获取文件信息失败" });
        }
    }

    /// <summary>
    /// 验证文件
    /// </summary>
    /// <param name="file">要验证的文件</param>
    /// <returns>验证结果</returns>
    [HttpPost("validate")]
    public async Task<IActionResult> ValidateFile(IFormFile file)
    {
        try
        {
            if (file == null)
            {
                return BadRequest(new { message = "请选择要验证的文件" });
            }

            var result = await _fileUploadService.ValidateFileAsync(file);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件验证失败");
            return StatusCode(500, new { message = "文件验证失败" });
        }
    }

    /// <summary>
    /// 清理过期文件
    /// </summary>
    /// <param name="expireDays">过期天数，默认7天</param>
    /// <returns>清理结果</returns>
    [HttpPost("cleanup")]
    [Authorize(Roles = "Admin")] // 仅管理员可以执行清理
    public async Task<IActionResult> CleanupExpiredFiles([FromQuery] int expireDays = 7)
    {
        try
        {
            var count = await _fileUploadService.CleanupExpiredFilesAsync(expireDays);
            return Ok(new { message = $"清理完成，共清理 {count} 个过期文件", count });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理过期文件失败");
            return StatusCode(500, new { message = "清理过期文件失败" });
        }
    }

    /// <summary>
    /// 上传头像（用户专用）
    /// </summary>
    /// <param name="file">头像文件</param>
    /// <returns>上传结果</returns>
    [HttpPost("upload-avatar")]
    public async Task<IActionResult> UploadAvatar(IFormFile file)
    {
        try
        {
            if (file == null)
            {
                return BadRequest(new { message = "请选择头像文件" });
            }

            var result = await _fileUploadService.UploadFileAsync(file, "avatars");
            
            if (result.Succeeded)
            {
                return Ok(result);
            }
            
            return BadRequest(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "头像上传失败");
            return StatusCode(500, new { message = "头像上传失败" });
        }
    }

    /// <summary>
    /// 获取文件访问URL
    /// </summary>
    /// <param name="relativePath">相对路径</param>
    /// <returns>完整URL</returns>
    [HttpGet("url")]
    [AllowAnonymous] // 获取URL不需要认证
    public IActionResult GetFileUrl([FromQuery] string relativePath)
    {
        try
        {
            if (string.IsNullOrEmpty(relativePath))
            {
                return BadRequest(new { message = "相对路径不能为空" });
            }

            var url = _fileUploadService.GetFileUrl(relativePath);
            return Ok(new { url });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文件URL失败: {RelativePath}", relativePath);
            return StatusCode(500, new { message = "获取文件URL失败" });
        }
    }
}
